package com.parktech.sun.web.controller.management.action;

import com.parktech.sun.domain.model.Constants;
import com.parktech.sun.domain.model.addressbook.ContactGroup;
import com.parktech.sun.domain.model.addressbook.ContactMember;
import com.parktech.sun.domain.model.email.Email;
import com.parktech.sun.domain.model.sms.Sms;
import com.parktech.sun.domain.model.sms.SmsTemplate;
import com.parktech.sun.domain.model.sunhz.Enterprise;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.service.sunhz.*;
import com.parktech.sun.utils.TreeJsModel;
import com.parktech.sun.utils.action.MailSender;
import com.parktech.sun.utils.action.SmsProcessor;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by IntelliJ IDEA.
 * User: guo
 * Date: 11-1-12
 * Time: 下午11:48
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/management/action")
public class SmsController {
    private final String redirectFailedListURL = "redirect:listFailedSmses";
    private final String redirectSuccessListURL = "redirect:listSuccessSmses";
    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private SmsTemplateService smsTemplateService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private ContactGroupService contactGroupService;
    @Autowired
    private ContactMemberService contactMemberService;
    @Autowired
    private EnterpriseService enterpriseService;

    @RequestMapping(value = "/listSuccessSmses", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView listSuccessSmses(HttpServletRequest request) {
        Integer currentPageNo = request.getParameter("pageNo") != null ? Integer.parseInt(request.getParameter("pageNo").trim()) : 1;
        ModelAndView modelAndView = new ModelAndView("management/sms/smsSentList");
        List fieldColumns = new ArrayList();
        List searchValues = new ArrayList();
        fieldColumns.add("status");
        searchValues.add(Constants.ACTION_STATUS_SUCCESS);
        Page<Sms> returnPage = new Page<Sms>(Constants.PAGINATION_PAGE_SIZE, currentPageNo);
        returnPage.setTotalCount(smsService.getTotalSizeWithSimilarCondition(Sms.class, fieldColumns, searchValues));
        returnPage.setResult(smsService.getPaginationObjectsWithSimilarCondition(Sms.class, currentPageNo, Constants.PAGINATION_PAGE_SIZE, fieldColumns, searchValues, null, null));

        return modelAndView.addObject(returnPage);
    }

    @RequestMapping(value = "/listFailedSmses", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView listFailedSmses(HttpServletRequest request) {
        Integer currentPageNo = request.getParameter("pageNo") != null ? Integer.parseInt(request.getParameter("pageNo").trim()) : 1;
        ModelAndView modelAndView = new ModelAndView("management/sms/smsFailedList");
        List fieldColumns = new ArrayList();
        List searchValues = new ArrayList();
        fieldColumns.add("status");
        searchValues.add(Constants.ACTION_STATUS_FAILED);
        Page<Sms> returnPage = new Page<Sms>(Constants.PAGINATION_PAGE_SIZE, currentPageNo);
        returnPage.setTotalCount(smsService.getTotalSizeWithSimilarCondition(Sms.class, fieldColumns, searchValues));
        returnPage.setResult(smsService.getPaginationObjectsWithSimilarCondition(Sms.class, currentPageNo, Constants.PAGINATION_PAGE_SIZE, fieldColumns, searchValues, null, null));

        return modelAndView.addObject(returnPage);
    }

    @RequestMapping(value = "/manageSendSms",method = RequestMethod.GET)
    public String manageSendSms( Model model) {
         model.addAttribute(new Sms());
        return "management/sms/smsSendAdd";
    }

    @RequestMapping(value = "/saveManageSendSms",method = RequestMethod.POST)
    public String saveManageSendSms(@ModelAttribute Sms sms,Model model,HttpServletRequest request) throws InvocationTargetException, IllegalAccessException, ParseException {
        String contactMixStr = request.getParameter("contactMixStr");
        List<String> enterpriseIDList = new ArrayList<String>();
        List<String> contactMemberIDList = new ArrayList<String>();
        if (contactMixStr != null && (contactMixStr.indexOf("member_") != -1 || contactMixStr.indexOf("enterprise_") != -1)) {
            String[] contactMixStrArray = contactMixStr.split("#");
            for (String str : contactMixStrArray) {
                if (str != null && str.indexOf("member_") != -1 ) {
                    contactMemberIDList.add(str.substring(str.indexOf("member_") + 7));
                } else if (str != null && str.indexOf("enterprise_") != -1) {
                    enterpriseIDList.add(str.substring(str.indexOf("enterprise_") + 11));
                }
            }
        }
        //////////////////////////////////////////////////////////////////
        if (sms != null && !sms.isScheduleSend() && (contactMemberIDList.size() != 0 || enterpriseIDList.size() != 0)) {
            SmsProcessor smsProcessor=new SmsProcessor();
            for(String contactMemberID:contactMemberIDList)
            {
                ContactMember contactMember = contactMemberService.getBeanByID(Long.valueOf(contactMemberID));
                if(contactMember.getMobile()==null || contactMember.getMobile().length()<8)
                    continue;
                Sms newSms = new Sms();
                BeanUtils.copyProperties(newSms, sms);
                newSms.setId(null);
                newSms.setAcceptorSms(contactMember.getMobile());
                newSms.setToAcceptor(contactMember);
                String retMsg=smsProcessor.send(sms.getContent(), contactMember.getMobile());
                if(retMsg.equals("success")){
					newSms.setStatus(Constants.ACTION_STATUS_SUCCESS);
				}else{
					newSms.setStatus(Constants.ACTION_STATUS_FAILED);
				}
                if(newSms.isSaveHistory())
                {
                    smsService.saveOrUpdateBean(newSms);
                }
            }
            for (String enterpriseID : enterpriseIDList) {
                Enterprise enterprise = enterpriseService.getBeanByID(Long.valueOf(enterpriseID));
                if(enterprise.getPhone()==null || enterprise.getPhone().length()<8)
                    continue;
                Sms newSms = new Sms();
                BeanUtils.copyProperties(newSms, sms);
                newSms.setId(null);
                newSms.setAcceptorSms(enterprise.getPhone());
                newSms.setToAcceptor(enterprise);
                String retMsg=smsProcessor.send(sms.getContent(), enterprise.getPhone());
                if(retMsg.equals("success")){
					newSms.setStatus(Constants.ACTION_STATUS_SUCCESS);
				}else{
					newSms.setStatus(Constants.ACTION_STATUS_FAILED);
				}
                if(newSms.isSaveHistory())
                {
                    smsService.saveOrUpdateBean(newSms);
                }
            }
            return redirectSuccessListURL;
        }
        /////////////////////////////////////////////////////////////////////
        if (sms != null && sms.isScheduleSend() && (contactMemberIDList.size() != 0 || enterpriseIDList.size() != 0)) {
             String scheduleSendDate=request.getParameter("scheduleSendDate");
		    String scheduleSendHour=request.getParameter("scheduleSendHour");
		    String scheduleSendMinute=request.getParameter("scheduleSendMinute");
            String scheduleSendDatetime=scheduleSendDate+" "+scheduleSendHour+":"+scheduleSendMinute+":00";
            sms.setScheduleSendDatetime(dateFormat.parse(scheduleSendDatetime));
            for(String contactMemberID:contactMemberIDList)
            {
                ContactMember contactMember = contactMemberService.getBeanByID(Long.valueOf(contactMemberID));
                if(contactMember.getMobile()==null || contactMember.getMobile().length()<8)
                    continue;
                Sms newSms = new Sms();
                BeanUtils.copyProperties(newSms,sms);
                newSms.setId(null);
                newSms.setAcceptorSms(contactMember.getMobile());
                newSms.setToAcceptor(contactMember);
                smsService.saveOrUpdateBean(newSms);
            }
            for (String enterpriseID : enterpriseIDList) {
                Enterprise enterprise = enterpriseService.getBeanByID(Long.valueOf(enterpriseID));
                if(enterprise.getPhone()==null || enterprise.getPhone().length()<8)
                    continue;
                Sms newSms = new Sms();
                BeanUtils.copyProperties(newSms, sms);
                newSms.setId(null);
                newSms.setAcceptorSms(enterprise.getPhone());
                newSms.setToAcceptor(enterprise);
                smsService.saveOrUpdateBean(newSms);
            }
        }
        model.addAttribute(new Sms());
        return "management/sms/smsSendAdd";
    }

    @ModelAttribute("smsTemplateMap")
    public Map<String, String> getAllSmsTemplateMap() {
        Map<String, String> smsTemplateMap = new TreeMap<String, String>();
        smsTemplateMap.put("--请选择模板--","");
        List<SmsTemplate> smsTemplateList = smsTemplateService.getPaginationObjectsWithSimilarCondition(SmsTemplate.class, 1, 6666, null, null, null, null);
        for (SmsTemplate smsTemplate : smsTemplateList) {
            smsTemplateMap.put(smsTemplate.getName(), smsTemplate.getContent());
        }
        return smsTemplateMap;
    }

    @RequestMapping(value = "/deleteSuccessSmses",method = RequestMethod.POST)
    public String deleteSuccessSmses(HttpServletRequest request) {
        String[] successSmsIDArray = request.getParameter("selectedSuccessSmsIDArray")==null?new String[0]:request.getParameter("selectedSuccessSmsIDArray").trim().split(",");
        for (String successSmsID : successSmsIDArray) {
            smsService.removeBean(Long.valueOf(successSmsID.trim()));
        }
        return redirectSuccessListURL;
    }

    @RequestMapping(value = "/deleteFailedSmses",method = RequestMethod.POST)
    public String deleteFailedSmses(HttpServletRequest request) {
        String[] failedSmsIDArray = request.getParameter("selectedFailedSmsIDArray")==null?new String[0]:request.getParameter("selectedFailedSmsIDArray").trim().split(",");
        for (String failedSmsID : failedSmsIDArray) {
            smsService.removeBean(Long.valueOf(failedSmsID.trim()));
        }
        return redirectFailedListURL;
    }

    @ModelAttribute("treeJsModelList")
    public List<TreeJsModel> getTreeJsModelList() {
        List<TreeJsModel> treeJsModelList = new ArrayList<TreeJsModel>();
        List<ContactGroup> contactGroupList = contactGroupService.getPaginationObjectsWithSimilarCondition(ContactGroup.class, 1, 666, null, null, null, null);
        for (ContactGroup contactGroup : contactGroupList) {
            TreeJsModel treeJsModel = new TreeJsModel();
            treeJsModel.setParentNodeID("0");
            treeJsModel.setCurrentNodeID("group_"+contactGroup.getId());
            treeJsModel.setCurrentNodeName(contactGroup.getName());
            treeJsModelList.add(treeJsModel);
            if (contactGroup.getContactMembers().size() != 0) {
                treeJsModel.setHaveChild(true);
                for (ContactMember contactMember : contactGroup.getContactMembers()) {
                    TreeJsModel subJsModel = new TreeJsModel();
                    subJsModel.setParentNodeID("group_"+contactGroup.getId());
                    subJsModel.setHaveChild(false);
                    subJsModel.setCurrentNodeID("member_"+contactMember.getId());
                    subJsModel.setCurrentNodeName(contactMember.getName());
                    treeJsModelList.add(subJsModel);
                }
            }
        }

       ///////////////////////////////////////////////////////////////////////
        List<Enterprise> enterpriseList = enterpriseService.getPaginationObjectsWithSimilarCondition(Enterprise.class, 1, 99999, null, null, null, null);
        TreeJsModel treeJsModel = new TreeJsModel();
        treeJsModel.setParentNodeID("0");
        treeJsModel.setCurrentNodeID("father_1");
        treeJsModel.setCurrentNodeName("企业机构");
        treeJsModelList.add(treeJsModel);
        treeJsModel.setHaveChild(true);
        for (Enterprise enterprise : enterpriseList) {
            TreeJsModel subJsModel = new TreeJsModel();
            subJsModel.setParentNodeID("father_1");
            subJsModel.setHaveChild(false);
            subJsModel.setCurrentNodeID("enterprise_"+enterprise.getId());
            subJsModel.setCurrentNodeName(enterprise.getName());
            treeJsModelList.add(subJsModel);
        }
        return treeJsModelList;
    }
}

